#!/usr/bin/env python
# -*- coding: utf-8 -*-
 
import sys, os
import logging
import wsgiref.handlers
import twitter_oauth_key
from appengine_twitter import AppEngineTwitter
from basehandler import BaseHandler, h
from django.utils import simplejson
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template 
from google.appengine.api import urlfetch
 

FOOTER = """
<br>
<hr>
<small>
Powered by
<a href="http://0-oo.net/sbox/python-box/appengine-oauth">AppEngine-OAuth</a>, 
<a href="http://0-oo.net/sbox/python-box/appengine-twitter">AppEngine-Twitter</a>,
<a href="http://code.google.com/apis/ajaxsearch/">Google AJAX Search API</a>,
<a href="http://apiwiki.twitter.com/">Twitter API</a>
<br>
Project home: <a href="http://code.google.com/p/byoonview/">http://code.google.com/p/byoonview/</a>
<br>
Created by <a href="http://twitter.com/satohk">@satohk</a>
<small>
"""
 
 
class InitHandler(BaseHandler):
 
  def header(self):
    self.simple_header(u'Byoon')
 
    self.p('<h2>Byoon</h2>')
    self.p("<p>Visualize your friends_timeline in twitter.</p>")

  def footer(self):
    self.p(FOOTER)
    self.simple_footer()

  def get(self):
    sys.stderr.write("InitHandler.get")
    twitter = AppEngineTwitter()
    twitter.set_oauth(key=twitter_oauth_key.OAUTH_KEY, secret=twitter_oauth_key.OAUTH_SECRET)
 
    req_info = twitter.prepare_oauth_login()
 
    # request_tokenはcallbackされた後で使うのでDatastoreに保存しておく
    OAuthRequestToken(token=req_info['oauth_token'],
                      secret=req_info['oauth_token_secret']).put()
 
    self.header()
    self.p('<a href="' + h(req_info['url']) + '">')
    self.p(u'Login</a>', True)
    self.footer()
 
 
 
class CallbackHandler(BaseHandler):

  def loadCookie(self):
    if 'HTTP_COOKIE' in os.environ:
      cookies = os.environ['HTTP_COOKIE'].split('; ')
      dic = {}

      for cookie in cookies:
        key_val = cookie.split("=")
        dic[key_val[0]] = key_val[1]

      return dic
    else:
      return {}
 
  def get(self):
    oauth_token = ""
    oauth_token_secret = ""

    cookie = self.loadCookie()

    if 'OAUTH_TOKEN' not in cookie:
      twitter = AppEngineTwitter()
      twitter.set_oauth(twitter_oauth_key.OAUTH_KEY, twitter_oauth_key.OAUTH_SECRET)
      req_token = self.request.get('oauth_token')
 
      query = OAuthRequestToken.all()
      query.filter('token = ', req_token)
      req_tokens = query.fetch(1)
 
      res = twitter.exchange_oauth_tokens(req_token, req_tokens[0].secret)
      oauth_token = res['oauth_token']
      oauth_token_secret = res['oauth_token_secret']

      req_tokens[0].delete()

      self.response.headers.add_header('Set-Cookie', 'OAUTH_TOKEN=%s' % oauth_token)
      self.response.headers.add_header('Set-Cookie', 'OAUTH_TOKEN_SECRET=%s' % oauth_token_secret)
    else:
      oauth_token = cookie['OAUTH_TOKEN']
      oauth_token_secret = cookie['OAUTH_TOKEN_SECRET']

    template_values = {
      'twitter_access_token': oauth_token,
      'twitter_access_token_secret': oauth_token_secret,
      'footer' : FOOTER,
    }

    template_path = os.path.join(os.path.dirname(__file__), 'callback_template.html')
    self.response.out.write(template.render(template_path, template_values))


class ProxyHandler(BaseHandler):
  def get(self):
    twitter = AppEngineTwitter()
    twitter.set_oauth(twitter_oauth_key.OAUTH_KEY, twitter_oauth_key.OAUTH_SECRET)

    path_array = self.request.path.split("/")
    path_array.pop(0)
    path_array.pop(0)
    path = "/".join(path_array)

    url = 'http://twitter.com/' + path + '?' + self.request.query_string
    res = urlfetch.fetch(url=url, method='GET')

    self.p(res.content, True)
    
 
 
#Model(s)
 
class OAuthRequestToken(db.Model):
  token = db.StringProperty()
  secret = db.StringProperty()
 
 
 
logging.getLogger()
routing = [('/', InitHandler),
           ('/callback', CallbackHandler),
           ('/proxy/.*', ProxyHandler)]
application = webapp.WSGIApplication(routing, debug=False)
wsgiref.handlers.CGIHandler().run(application)
